import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class NativeCommunication {
  static const MethodChannel _channel = MethodChannel('samples.flutter.dev/battery');

  static Future<int> getBatteryLevel() async {
    try {
      return await _channel.invokeMethod('getBatteryLevel');
    } catch (e) {
      return -1;
    }
  }

  static Future<void> showToast(String message) async {
    // await _channel.invokeMethod('showToast', {'message': message});
    await _channel.invokeMethod('showToast', message);
  }

  static Future<Map<String, dynamic>> getUserInfo() async {
    try {
      final result = await _channel.invokeMethod<Map<dynamic, dynamic>>('getUserInfo');
      return result?.cast<String, dynamic>() ?? {

      };
    } catch (e) {
      return {};
    }
  }

  static void setupMethodCallHandler() {
    print('初始化');
    _channel.setMethodCallHandler((MethodCall call) async {
      switch (call.method) {
        case 'updateUI':
          final String data = call.arguments;
          print('收到Android数据: $data');
          return true;
        default:
          throw PlatformException(
            code: 'UNIMPLEMENTED',
            message: '未实现的方法: ${call.method}',
            details: null,
          );
      }
    });
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int? _batteryLevel;
  String? _userName;

  @override
  void initState() {
    super.initState();
    // 初始化MethodChannel处理器
    NativeCommunication.setupMethodCallHandler();
    _getBatteryLevel();
    _getUserInfo();
  }

  Future<void> _getBatteryLevel() async {
    final int batteryLevel = await NativeCommunication.getBatteryLevel();
    setState(() {
      _batteryLevel = batteryLevel;
    });
  }

  Future<void> _getUserInfo() async {
    final userInfo = await NativeCommunication.getUserInfo();
    setState(() {
      _userName = userInfo['name'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Flutter与Android通信')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('电池电量: $_batteryLevel%'),
            if (_userName != null) Text('用户名: $_userName'),
            ElevatedButton(
              onPressed: () => NativeCommunication.showToast('来自Flutter的消息'),
              child: Text('显示Toast'),
            ),
            ElevatedButton(
              onPressed: () =>{
                NativeCommunication.getUserInfo()
              },
              child: Text('获取用户信息'),
            ),
          ],
        ),
      ),
    );
  }
}